package com.premnirmal.Magnet.app;

import com.premnirmal.magnet.library.IconCallback;
import com.premnirmal.magnet.library.Magnet;
import cs.help.tool.Log;
import cs.help.tool.Toast;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.window.service.WindowManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.sysappcomponents.settings.AppSettings;
import ohos.utils.net.Uri;

import java.io.IOException;

import static ohos.agp.components.element.ShapeElement.LINEAR_GRADIENT_SHADER_TYPE;


public class ParanormalAbility extends Ability implements IconCallback, Component.ClickedListener {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);

        checkPermission();
        initView();
    }

    private void initView() {
        findComponentById(ResourceTable.Id_start).setClickedListener(this);
        findComponentById(ResourceTable.Id_stop).setClickedListener(this);
    }

    public boolean checkPermission() {
        if (AppSettings.canShowFloating(this)) {
            addWindow();
            return true;
        } else {
            Intent intent1 = new Intent();
            Uri parse = Uri.parse("package:" + getBundleName());
            Intent.OperationBuilder builder=new Intent.OperationBuilder()
                    .withAction("android.settings.action.MANAGE_OVERLAY_PERMISSION")
                    .withUri(parse);
            intent1.setOperation(builder.build());
            startAbilityForResult(intent1, 1000);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == 1000) {
            boolean b = AppSettings.canShowFloating(this);
            if (b) {
                addWindow();
            }
        }
    }

    private Magnet magnet;

    public void addWindow() {
//        PixelMap pixelMap = Util.getPixelMap(this, ResourceTable.Media_icon);

        Resource resource = null;
        try {
            resource = getResourceManager().getResource(ResourceTable.Media_icon);
        } catch (IOException | NotExistException e) {
            e.printStackTrace();
        }
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.desiredSize = new Size(AttrHelper.vp2px(60, this), AttrHelper.vp2px(60, this));
        PixelMap pixelMap = ImageSource.create(resource, null).createPixelmap(decodingOptions);


        Image image = new Image(this);
        image.setPixelMap(pixelMap);
        image.setClickedListener(component -> {
            Log.i("MainAbility.onClick([component]):76     destroyWindow前" + WindowManager.getInstance().getTopWindow());
            Log.i("MainAbility.onClick([component]):76     destroyWindow后" + WindowManager.getInstance().getTopWindow());
        });

        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColors(new RgbColor[]{RgbColor.fromArgbInt(0x05000000), RgbColor.fromArgbInt(0x80000000)});
        shapeElement.setOrientation(ShapeElement.Orientation.TOP_TO_BOTTOM);
        shapeElement.setShaderType(LINEAR_GRADIENT_SHADER_TYPE);


        if (magnet == null) {
            magnet = new Magnet.Builder(this)
                    .setIconView(image)
                    .setIconCallback(this)
                    .setHideFactor(0.2f)
                    .setShouldShowRemoveView(true)
                    .setRemoveIconResId(new VectorElement(this, ResourceTable.Graphic_ic_close))
                    .setRemoveIconShadow(shapeElement)
                    .setShouldStickToWall(true)
                    .setRemoveIconShouldBeResponsive(true)
                    .setInitialPosition(200, AttrHelper.vp2px(30, this))
                    .build();
        }
    }



    @Override
    public void onFlingAway() {
        if (magnet != null) {
            magnet.destroy();
            magnet = null;
        }
    }

    @Override
    public void onMove(float x, float y) {
        Log.i("MainAbility.onMove([x, y]):124    " + x + "　　　　" + y);
    }


    @Override
    protected void onStop() {
        super.onStop();
        onFlingAway();
    }

    @Override
    public void onIconClick(Component icon, float iconXPose, float iconYPose) {
        Toast.show(this, ResourceTable.String_click);
    }

    @Override
    public void onIconDestroyed() {

    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {

            case ResourceTable.Id_start:
                if (checkPermission()) {
                    if (magnet == null) {
                        addWindow();
                    }
                    magnet.show();
                } else {
                    Toast.show(this, "请前往设置开启悬浮窗权限");
                }
                break;
            case ResourceTable.Id_stop:
                if (magnet != null) {
                    magnet.destroy();
                    magnet = null;
                }
                break;
        }
    }
}
